package com.qf.fmall01.service.impl;

import com.qf.fmall01.dao.UserMapper;
import com.qf.fmall01.entity.User;
import com.qf.fmall01.service.UserService;
import com.qf.fmall01.utils.JwtUtils;
import com.qf.fmall01.utils.MD5Utils;
import com.qf.fmall01.vo.ResStatus;
import com.qf.fmall01.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public  synchronized ResultVO userResgit(String name, String pwd) {
        ResultVO vo = new ResultVO();
        // 根据用户名去数据库查询用户名对应的用户信息
        User condition = new User();
        condition.setUsername(name);
        User user = userMapper.selectOne(condition);
        if (user == null) { // 插入用户
            User newUSer = new User();
            newUSer.setUsername(name);
            newUSer.setPassword(MD5Utils.md5(pwd));
            newUSer.setUserRegtime(new Date());
            newUSer.setUserModtime(new Date());

            int i = userMapper.insert(newUSer);
            if(i == 1){
                vo.setCode(ResStatus.OK);
                vo.setMsg("新增用户成功");
                vo.setData(newUSer);
            }else{
                vo.setCode(ResStatus.NO);
                vo.setMsg("数据库操作异常");
            }

        }else{
            vo.setCode(ResStatus.NO);
            vo.setMsg("当前用户名以存在，不可以注册");
        }

        return vo;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResultVO checkLogin(String name, String pwd) {

        ResultVO vo = new ResultVO();
        // 根据用户名去数据库查询用户名对应的用户信息
        User condition = new User();
        condition.setUsername(name);
        User user = userMapper.selectOne(condition);
        if (user == null) {
            vo.setCode(ResStatus.LOGIN_FAILED);
            vo.setMsg("用户名不存在");
        }else{
            String dbPassword = user.getPassword(); // 数据库中的密码
            String newPassword = MD5Utils.md5(pwd);
            if (dbPassword.equals(newPassword)){
                vo.setCode(ResStatus.OK);
                // 生成一个token字符串
//                String token = user.getUsername()+":QIANfeng6666";
//                String encode = Base64Utils.encode(token);
                String token = JwtUtils.createToken(user.getUsername(), user.getUserId() + "");
                vo.setMsg(token);
                vo.setData(user);
            }else{
                vo.setCode(ResStatus.LOGIN_FAILED);
                vo.setMsg("密码错误");
            }
        }
        return vo;
    }
}
